#! usr/bin/node;

const log = console.log;

let buf1 = new Buffer(256);
buf1[0] = 0;

log(`buf1 length: ${buf1.length}\n`);
log(buf1);

//通过循环，来初始化 buffer 中的每个字节
for(let i=0; i<buf1.length; i++){
  buf1[i] = i;
}
log('buf1:', buf1);

//类似数组，对buffer做切片操作
let buf2 = buf1.slice(250, 256);
log('buf2:', buf2);
//在buffer中填充数据，buffer数据转化成JSON数据
buf2.fill(0);
log('\nbuf2:', buf2);
log('\nbuf2:JSON', buf2.toJSON());
log('\nbuf2:str', JSON.stringify(buf2));

//用数组初始化buffer
let arr = ['a', 0xdf,0xba, 0, 255, 10];
let buf3 = new Buffer(arr);
log('\nbuf3:', buf3);

//用字符串初始化buffer
let str = 'hello world';
let buf4 = new Buffer(str);
log('\nbuf4:', buf4);
//buffer数据复制
buf4.copy(buf3, 0, 0, buf4.length);
log('\nbuf3:', buf3);

//UTF8编码
let str2 = '你好 wd';
let buf5 = new Buffer(str2, 'utf8');
log('\nbuffer length:', buf5.length);
log('\nbuffer content:', buf5);
log('\nstrign length:', str.length);
